import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import {
	login,
	logout,
	getInfo,
	getSimple,
	getAreaTree
} from '@/api/login'

const baseUrl = config.baseUrl

const system = {
	state: {
		menus: storage.get(constant.menus),
		dict: storage.get(constant.dict),
		areaTree: storage.get(constant.areaTree)
	},

	mutations: {
		SET_MENUS: (state, menus) => {
			state.menus = menus
			storage.set(constant.menus, menus)
		},
		SET_DICT: (state, dict) => {
			state.dict = dict
			storage.set(constant.dict, dict)
		},
		SET_AREA_TREE: (state, areaTree) => {
			state.areaTree = areaTree
			storage.set(constant.areaTree, areaTree)
		}
	},

	actions: {
		getAreaTreeData({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				// 先检查内存中是否有数据
				if (state.areaTree) {
					resolve(state.areaTree)
					return
				}
				
				// 再检查本地存储中是否有数据
				let data = storage.get(constant.areaTree)
				if (data) {
					commit('SET_AREA_TREE', data)
					resolve(data)
					return
				}
				
				// 如果都没有，则从API获取
				getAreaTree().then(res => {
					commit('SET_AREA_TREE', res)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		simple({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getSimple().then(res => {
					const dictDataMap = {};
					res.forEach((dictData) => {
						// 获得 dictType 层级
						if (!dictDataMap[dictData.dictType]) {
							dictDataMap[dictData.dictType] = [];
						}

						// 处理 dictValue 层级
						dictDataMap[dictData.dictType].push({
							value: dictData.value,
							label: dictData.label,
							colorType: dictData.colorType,
							cssClass: dictData.cssClass
						});
					});
					console.log(dictDataMap)
					commit('SET_DICT', dictDataMap)
					resolve(dictDataMap)
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
}

export default system